package win.somereason.test.baseline_web.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import win.somereason.test.baseline_web.biz.CarBiz;
import win.somereason.test.baseline_web.common.CodeEnumUtil;
import win.somereason.test.baseline_web.entity.Car;
import win.somereason.test.baseline_web.entity.CarBrand;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;

/**
 * Created by Qingsheng.Sun on 2018/3/12.
 */
@Controller
@RequestMapping("car")
public class CarController {

    @Autowired
    CarBiz carBiz;

    @RequestMapping("index")
    public ModelAndView index() {
        ModelAndView mv = new ModelAndView();
        mv.addObject("cars", carBiz.queryAll());
        return mv;
    }

    @RequestMapping("detail")
    public ModelAndView detail(Integer id) {
        ModelAndView mv = new ModelAndView();
        mv.addObject("car", carBiz.queryById(id));
        return mv;
    }

    @RequestMapping("add")
    public ModelAndView add() {
        ModelAndView mv = new ModelAndView();
        mv.addObject("errorInfo", "");
        return mv;
    }


    @RequestMapping(value = "doadd", method = RequestMethod.POST)
    @ResponseBody
    public String doAdd(Car car, BindingResult bindingResult) {
        String ret = "OK";
        try {
            carBiz.add(car);
        } catch (Exception ex) {
            ret = ex.getMessage();
        }
        return ret;
    }

    @RequestMapping(value = "doadd1", method = RequestMethod.POST)
    @ResponseBody
    public String doAdd1(HttpServletRequest request) {
        String ret = "OK";
        Car car = new Car();
        car.setBrand(CodeEnumUtil.codeOf(CarBrand.class, Integer.parseInt(request.getParameter("brand"))));
        car.setBuyDate(LocalDate.parse(request.getParameter("buyDate")));
        car.setColor(request.getParameter("color"));
        car.setModel(request.getParameter("model"));
        car.setName(request.getParameter("name"));
        car.setPower(Double.parseDouble(request.getParameter("power")));
        try {
            carBiz.add(car);
        } catch (Exception ex) {
            ret = ex.getMessage();
        }
        return ret;
    }
}
